import React, { useState, useEffect } from 'react';
import { Button, Avatar, Dropdown, Space, Typography, message, Card } from 'antd';
import { useLocation, useRoutes } from 'react-router-dom';
import { RouterList } from './routers';
import {
	UserOutlined,
	LogoutOutlined,
	HomeOutlined,
	ProjectOutlined,
	TeamOutlined,
	FileTextOutlined,
	BarChartOutlined,
	SettingOutlined,
	LoginOutlined
} from '@ant-design/icons';
import './index.css';
import { useNavigate } from 'react-router-dom';
const { Text, Title } = Typography;
interface UserInfo {
	id: string;
	name: string;
	email: string;
	role: string;
	role_name: string;
	avatar?: string;
}
const App: React.FC = () => {
	const navigate = useNavigate();
	const { pathname } = useLocation();
	const [userInfo, setUserInfo] = useState<UserInfo | null>(null);
	const [isLoggedIn, setIsLoggedIn] = useState(false);
	const [activeKey, setActiveKey] = useState('home');
	const [loading, setLoading] = useState(true);

	useEffect(() => {
		const checkAuth = async () => {
			try {
				setLoading(true);
				const token = localStorage.getItem('token');
				const userData = localStorage.getItem('userinfo');

				if (token && userData) {
					const user = JSON.parse(userData);
					setUserInfo(user);
					setIsLoggedIn(true);

					// 根据当前路径设置activeKey
					const currentItem = navItems.find(item => item.path === pathname);
					if (currentItem) {
						setActiveKey(currentItem.key);
					} else {
						// 如果路径不在导航中，默认选中首页
						setActiveKey('home');
					}
				} else {
					// 未登录时强制跳转首页
					if (pathname !== '/') {
						navigate('/');
					}
				}
			} catch (error) {
				console.error('验证登录状态失败:', error);
				message.error('验证登录状态失败');
			} finally {
				setLoading(false);
			}
		};

		checkAuth();
	}, [pathname, navigate]);

	const handleLogin = () => {
		navigate('/login');
	};
	const handleLogout = () => {
		localStorage.removeItem('token');
		localStorage.removeItem('userinfo');
		setUserInfo(null);
		setIsLoggedIn(false);
		setActiveKey('home');
		navigate('/');
		message.success('已退出登录');
	};
	const userDropdown = [
		{
			key: '1',
			label: (
				<Space>
					<UserOutlined />
					<span>个人中心</span>
				</Space>
			),
			onClick: () => navigate('/profile')
		},
		{
			key: '2',
			label: (
				<Space>
					<LogoutOutlined />
					<span>退出登录</span>
				</Space>
			),
			onClick: handleLogout
		}
	];
	const navItems = [
		{ key: 'home', icon: <HomeOutlined />, label: '首页', path: '/', auth: true },
		{ key: 'project', icon: <ProjectOutlined />, label: '项目管理', path: '/project', auth: true },
		{ key: 'team', icon: <TeamOutlined />, label: '团队协作', path: '/team', auth: true },
		{ key: 'docs', icon: <FileTextOutlined />, label: '文档管理', path: '/docs', auth: true },
		{ key: 'data', icon: <BarChartOutlined />, label: '数据分析', path: '/data', auth: true },
		{
			key: 'system',
			icon: <SettingOutlined />,
			label: '系统管理',
			path: '/system',
			auth: userInfo?.role === 'admin' || userInfo?.role === 'super_admin'
		}
	];

	const handleNavClick = (path: string, auth: boolean, key: string) => {
		if (!auth) {
			message.warning('您没有权限访问此页面');
			return;
		}
		if (!isLoggedIn) {
			message.warning('请先登录');
			navigate('/login');
			return;
		}
		setActiveKey(key);
		navigate(path);
	};

	// 是否是登录注册页
	const isAuthPage = ['/login', '/register'].includes(pathname);
	// 是否是首页
	const isHomePage = pathname === '/';

	if (loading) {
		return <div className="loading-container">加载中...</div>;
	}

	return (
		<>
			{useRoutes(RouterList)}
			{!isAuthPage && (
				<div className="app-container">
					<header className="app-header">
						<div className="nav">
							<nav className="main-nav">
								{navItems.map(item => (
									<Button
										key={item.key}
										className={`nav-button ${activeKey === item.key ? 'active' : ''}`}
										icon={item.icon}
										onClick={() => handleNavClick(item.path, item.auth, item.key)}
										disabled={!isLoggedIn && item.key !== 'home'}
									>
										{item.label}
									</Button>
								))}
							</nav>
						</div>
						<div className="user-info-container">
							{isLoggedIn && userInfo ? (
								<Dropdown menu={{ items: userDropdown }} placement="bottomRight">
									<Space className="user-info">
										<Avatar
											size="default"
											icon={<UserOutlined />}
											src={userInfo.avatar}
											className="user-avatar"
										/>
										<div className="user-details">
											<Text strong className="user-name">{userInfo.name}</Text>
											<Text type="secondary" className="user-role">{userInfo.role_name}</Text>
										</div>
									</Space>
								</Dropdown>
							) : (
								<div className="login-prompt">
									<Button
										type="primary"
										className="login-btn"
										icon={<LoginOutlined />}
										onClick={handleLogin}
									>
										登录
									</Button>
								</div>
							)}
						</div>
					</header>

					<main className='app-main'>
						{isHomePage ? (
							<div className="home-content">
								<Card className="welcome-card">
									<Title level={2}>欢迎使用系统管理平台</Title>
									<p>一个基于React和Ant Design构建的管理系统</p>

									{!isLoggedIn ? (
										<div className="login-notice">
											<div className="notice-icon">
												<UserOutlined />
											</div>
											<p>您当前尚未登录，请先登录以访问完整功能</p>
											<Button
												type="primary"
												size="large"
												icon={<LoginOutlined />}
												onClick={handleLogin}
											>
												立即登录
											</Button>
										</div>
									) : (
										<div className="welcome-message">
											<p>您好，{userInfo?.name}！欢迎回来</p>
											<p>当前角色: {userInfo?.role_name}</p>
											<p>请选择上方导航菜单进入相应功能模块</p>
										</div>
									)}
								</Card>
							</div>
						) : (
							<div id='Container' className="sub-app-container"></div>
						)}
					</main>
				</div>
			)}
		</>
	);
};

export default App;